﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SmartSpace.UI.Silverlight;

namespace DynamicChart.UI
{
    public partial class ChartPackageView : AppView
    {
        private string _module;
        private DynamicChart.UI.ServiceRef.DateRange _dateRange;
        private int _curYear;
        private DynamicChart.UI.ServiceRef.ChartPackage _package;
        private List<FrameworkElement> _chartParts;

        public ChartPackageView()
            :base (new Guid("{70A4B756-106C-4072-AFD7-03D717E69A03}"), "chart package view")
        {
            InitializeComponent();

            _chartParts = new List<FrameworkElement>();
        }

        internal ChartPackageView(string module)
            : this()
        {
            _module = module;
        }

        internal ChartPackageView(string module, DynamicChart.UI.ServiceRef.DateRange dateRange)
            : this(module)
        {
            _dateRange = dateRange;
        }

        public override string GetCaption()
        {
            return _curYear.ToString();
        }

        protected override void OnExtendShown()
        {
            if (IsFirstDisplay)
            {
                if (string.IsNullOrEmpty(_module))
                {
                    _module = this.Arguments["module"].ToString();
                }

                this._ctlDateSlider.DateRangeChanged += new Action<string, DateTime>(_ctlDateSlider_DateRangeChanged);
                this._ctlDateSlider.Enter += new Action<DynamicChart.UI.ServiceRef.DateRange>(_ctlDateSlider_Enter);
                this._ctlDateSlider.ClickYear += new Action<ServiceRef.DateRange>(_ctlDateSlider_ClickYear);

                LoadPackage();
            }

            base.OnExtendShown();
        }

        private void LoadPackage()
        {
            DynamicChart.UI.ServiceRef.DynamicChartWebServiceSoapClient client = DynamicChartModule.CreateProxy();

            client.GetPackageCompleted += new EventHandler<DynamicChart.UI.ServiceRef.GetPackageCompletedEventArgs>(client_GetPackageCompleted);
            client.GetPackageAsync(_module, _dateRange, string.Format("year={0}", _curYear));
        }

        void client_GetPackageCompleted(object sender, DynamicChart.UI.ServiceRef.GetPackageCompletedEventArgs e)
        {
            if (e.Result != null)
            {
                _chartParts.Clear();
                _package = e.Result;

                #region 生成布局Grid
                _ctlPanel.RowDefinitions.Clear();
                _ctlPanel.ColumnDefinitions.Clear();
                _ctlPanel.Children.Clear();

                Grid container = null;

                if (e.Result.CellWidth != 0 || e.Result.CellHeight != 0)
                {
                    Grid containerTemp = new Grid();
                    containerTemp.Background = new SolidColorBrush(Color.FromArgb(0x01, 0x00, 0x00, 0x00));
                    ScrollViewer viewer = new ScrollViewer();
                    if (e.Result.CellWidth != 0)
                    {
                        viewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
                    }
                    else
                    {
                        viewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled;
                    }

                    if (e.Result.CellHeight != 0)
                    {
                        viewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
                    }
                    else
                    {
                        viewer.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;
                    }

                    viewer.Content = containerTemp;

                    _ctlPanel.Children.Add(viewer);

                    container = containerTemp;
                }
                else
                {
                    container = _ctlPanel;
                }

                int rowCount = 0;
                int colCount = 0;
                foreach (var item in e.Result.ChartDefinitions)
                {
                    if (item.Row >= rowCount)
                    {
                        rowCount += (item.Row - rowCount) + 1;
                    }

                    if (item.Col >= colCount)
                    {
                        colCount += (item.Col - colCount) + 1;
                    }
                }

                for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
                {
                    RowDefinition rowDef = new RowDefinition();
                    container.RowDefinitions.Add(rowDef);
                }

                for (int colIndex = 0; colIndex < colCount; colIndex++)
                {
                    ColumnDefinition colDef = new ColumnDefinition();
                    container.ColumnDefinitions.Add(colDef);
                }
                #endregion

                #region 创建图表
                foreach (var item in e.Result.ChartDefinitions)
                {
                    FrameworkElement part = null;

                    if (item.IsPackage)
                    {
                        part = new DynamicChart.UI.ChartPartDecorator();

                        (part as DynamicChart.UI.ChartPartDecorator).Enter += new EventHandler(part_Enter);
                    }
                    else
                    {
                        part = new DynamicChart.UI.ChartPart();
                    }

                    #region 设置大小
                    if (e.Result.CellWidth != 0 && item.RowSpan <= 1)
                    {
                        part.Width = e.Result.CellWidth;
                    }

                    if (e.Result.CellHeight != 0 && item.ColSpan <= 1)
                    {
                        part.Height = e.Result.CellHeight;
                    }
                    #endregion

                    part.Tag = item;

                    part.Margin = new Thickness(5, 5, 0, 0);
                    container.Children.Add(part);
                    Grid.SetRow(part, item.Row);
                    Grid.SetColumn(part, item.Col);
                    Grid.SetRowSpan(part, item.RowSpan);
                    Grid.SetColumnSpan(part, item.ColSpan);

                    _chartParts.Add(part);
                }
                #endregion

                #region 初始化时间条 - 触发时间变更，加载数据
                if (_package.DateRange == null || !_package.DateRange.IsVisible)
                {
                    _ctlDateSlider.SetDateRange(_package.DateRange);
                    _ctlDateSlider.Visibility = System.Windows.Visibility.Collapsed;
                }
                else
                {
                    _ctlDateSlider.SetDateRange(_package.DateRange);
                    _ctlDateSlider.Visibility = System.Windows.Visibility.Visible;
                }
                #endregion
            }
        }

        private void LoadChartDatas()
        {
            foreach (var item in _chartParts)
            {
                (item as IChartPart).IsBusy();

                DynamicChart.UI.ServiceRef.ChartDefinition chartDef = item.Tag as DynamicChart.UI.ServiceRef.ChartDefinition;
                if (_ctlDateSlider.DateRange.IsVisible)
                {
                    chartDef.DateRange = _ctlDateSlider.DateRange;
                }
                DynamicChart.UI.ServiceRef.DynamicChartWebServiceSoapClient client = DynamicChartModule.CreateProxy();
                client.GetDataCompleted += new EventHandler<DynamicChart.UI.ServiceRef.GetDataCompletedEventArgs>(client_GetDataCompleted);
                client.GetDataAsync(chartDef.Module, chartDef.DateRange, "", item);
            }
        }

        void client_GetDataCompleted(object sender, DynamicChart.UI.ServiceRef.GetDataCompletedEventArgs e)
        {
            //DynamicChart.ChartPart part = e.UserState as DynamicChart.ChartPart;
            DynamicChart.UI.IChartPart part = e.UserState as DynamicChart.UI.IChartPart;

            part.SetChartData(e.Result.Data);
        }

        void _ctlDateSlider_DateRangeChanged(string mode, DateTime currentDate)
        {
            LoadChartDatas();
        }

        void _ctlDateSlider_Enter(DynamicChart.UI.ServiceRef.DateRange dateRange)
        {
            this.SwitchView(new ChartPackageView(_module, dateRange));
        }

        void part_Enter(object sender, EventArgs e)
        {
            FrameworkElement part = sender as FrameworkElement;
            DynamicChart.UI.ServiceRef.ChartDefinition chartDefinition = part.Tag as DynamicChart.UI.ServiceRef.ChartDefinition;
            this.SwitchView(new ChartPackageView(chartDefinition.Module, _ctlDateSlider.DateRange));
        }

        void _ctlDateSlider_ClickYear(ServiceRef.DateRange obj)
        {
            this.GoBack();
        }
    }
}
